<?php
namespace app\hotback\controller;
use app\common\enum\OrderEnum;
use think\Db;
use app\service\TechnLastService;
use app\service\OrderService;
class Orderss extends Base
{
	public function _initialize()
	{
		// 调用父类前置方法
		parent::_initialize();

		// 登录校验
		$this->IsLogin();
	}
    public static $status_array = [
		3 => ['value' => 3, 'name' => '未审核'],
		1 => ['value' => 1, 'name' => '已通过'],
		2 => ['value' => 2, 'name' => '已驳回'],
	];
	/**
	 * 服务列表
	 */
	public function index()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		if(request()->isPost())
		{
			$params = input();
			if(!empty($params['page']) && !empty($params['limit']))
			{

                $map = [];
                

                $count = Db::name('order_budan')
                    ->where($map)
                    ->count();


                $list_data = Db::name('order_budan')
                    ->where($map)
                    ->limit(($params['page']-1)*$params['limit'],$params['limit'])
                    ->order('add_time desc')
                    ->select();
                    
                if(!empty($list_data))
				{
					$status_array = self::$status_array;
					//遍历处理
					foreach($list_data as $key => $value)
					{
						//审核url
						$list_data[$key]['audit_url'] = url('orderss/auditinfo', ['id' => $value['id']]);
					    
                        $list_data[$key]['add_time'] = date("Y-m-d H:i:s",$value['add_time']);
                        $order_id = Db::name('order')->where('order_no',$value['order_no'])->value('id');
                        $order_title = '';
                        if (!empty($order_id)){
                            $order_title = Db::name('order_detail')->where('order_id',$order_id)->value('title');
                        }
                        $list_data[$key]['order_title'] = $order_title;
                        $list_data[$key]['techn_name'] = Db::name('techn')->where('id',$value['techn_id'])->value('nickname');

					    //打款状态
					    $list_data[$key]['status_name'] = !empty($status_array[$value['type']]['name']) ? $status_array[$value['type']]['name'] : '';
					}
					$result['code'] = 0;
	        		$result['msg'] = "请求成功";
	        		$result['data'] = $list_data;
	        		$result['count'] = $count;
				}else
				{
					$result['code'] = -1;
	        		$result['msg'] = "暂无数据";
				}
			}
			echo json_encode($result);
		}else
		{
			return $this->fetch();
		}
	}



    /**
	 * 提现审核页面 
	 */
	public function auditinfo()
	{
		$params = input();
	    //查询
		$info = Db::name('order_budan')->where(['id' => $params['id']])->find();
			
		$this->assign('info',$info);
		
		return $this->fetch();
	}

	public function audit()
	{
	    if(request()->isPost())
		{
			$params = input();
			
			$order=Db::name('order_budan')->where(['id' => $params['id']])->find();
			
			if($order['type']!=3){
			    echo json_encode(['code' => -1, 'msg' => '已处理的申请']);
    			exit();
			}
			
	        $order_no = $order['order_no'];
		
		    //查询订单信息
            $order_info = Db::name('order')->where(['order_no' => $order_no])->find();
            
    		if($order_info['order_model']!=0||$order_info['techn_is_repair']!=1||$order_info['techn_repair_sid']!=0)
    		{
    			echo json_encode(['code' => -1, 'msg' => '该订单不需要补单']);
    			exit();
    		}
                
			if($params['type']==1){
                //dump($order_info);
                if(empty($order_info))
                {
                	echo json_encode(['code' => -1, 'msg' => '订单不存在']);
                    exit();
                }
                if($order_info['techn_is_repair'] != 1 || $order_info['techn_repair_sid'] != 0)
                {
                	echo json_encode(['code' => -1, 'msg' => '无需补单']);
                    exit();
                }
                //技师升级
                TechnLastService::TechnLevelUpgradeHandle($order_info['techn_id']);
                //查询是否有机构信息
                
                
                // 开启事务
		        Db::startTrans();
                // 订单主信息
                $order = [
                	'pid' => $order_info['id'],
                	'order_no' => date('YmdHis').GetRandomStr(6,'int'),
                	'techn_id' => $order_info['techn_id'],
                	'user_id' => $order_info['user_id'],
                	'user_note' => $order_info['user_note'],
                	'payment_id' => 1,
			        'status' => OrderEnum::ORDER_BU_SHENSU,
			        'pay_status' => 1,
                	'buy_number_duration' => $order_info['buy_number_duration'],
                	'pre_start_time' => $order_info['pre_start_time'],
                	'pre_end_time' => $order_info['pre_end_time'],
                	'travel_id' => $order_info['travel_id'],
                	'distance' => $order_info['distance'],
                	'price' => $order_info['price'],
                	'travel_price' => $order_info['travel_price'],
                	'total_price' => $order_info['price'],
                	//'total_price' => 0.01,
                	'client_type' => "pc",
                	'order_model' => 1,
			        'pay_price' => 0,
                	'proxy_id' => $order_info['proxy_id'],
                	'sheng' => $order_info['sheng'],
                	'shi' => $order_info['shi'],
                	'qu' => $order_info['qu'],
                	'add_time' => time(),
                	'upd_time' => time(),
                	'pay_time' => 0
                ];
                // 订单添加
                $order_id = Db::name('order')->insertGetId($order);
                if($order_id <= 0)
        		{
        			Db::rollback();
        			//支付日志添加失败
        			exit();
        		}
                // 订单状态日志添加
                $status_array = OrderService::$status_array;
                $order_status_history_id = Db::name('order_status_history')->insertGetId([
        			'order_id' => $order_info['id'],
        			'original_status' => 0,
        			'new_status' => 11,//申诉补单
        			'msg' => '技师申诉补单完成['.$status_array[0]['name'].'-'.$status_array[6]['name'].']',
        			'identity_type' => 'system',
        			'identity_id' => 0,
        			'add_time' => time()
        		]);
			    if($order_status_history_id <= 0)
        		{
        			Db::rollback();
        			//支付日志添加失败
        			exit();
        		}
//        		//写入结算数据
//        		$balance_data = [];
//        		//结算剩余百分比
//        		$balance_surplus_scale = 100;
//        		//服务剩余费用
//        		$balance_surplus_price = $order_info['price'];
//        		//查询技师等级写入结算数据
//        		//查询技师实时数据
//        		$techn_last_info = Db::name('techn_last')->where(['techn_id' => $order_info['techn_id']])->find();
//        		if(!empty($techn_last_info))
//        		{
//
//        		    if(!empty($techn_last_info['divide_into'])){
//
//        				//如果技师等级存在
//        				//结算服务分成
//        				if($balance_surplus_price >= 0.01)
//        				{
//        					//技师分成比例
//        					$techn_divide_into = $techn_last_info['divide_into'];
//        					//技师分成金额
//        					$techn_no_money = PriceNumberFormat(($techn_divide_into/100)*$order_info['price']);
//        					//技师服务费用结算数据
//        					$techn_service_data = [
//        						'balance_type' => 1,
//        						'order_id' => $order_info['id'],
//        						'identity_type' => 'techn',
//        						'identity_id' => $order_info['techn_id'],
//        						'divide_into' => $techn_divide_into,
//        						'price' => $order_info['price'],
//        						'no_money' => $techn_no_money >= 0.01 ? $techn_no_money : $order_info['price'],
//        						'yes_money' => $techn_no_money >= 0.01 ? $techn_no_money : $order_info['price'],
//        						'msg' => '技师分成',
//        						'status' => 1,
//        						'add_time' => time(),
//        						'upd_time' => time()
//        					];
//        					$balance_surplus_scale -= $techn_service_data['divide_into'];
//        					$balance_surplus_price -= $techn_service_data['no_money'];
//        					$balance_data[] = $techn_service_data;
//        				}
//
//        		    }else{
//        		        //如果技师实时信息存在查询对应等级
//            			//检查等级条件
//            			$techn_level_map = [
//            				'is_delete_time' => 0,
//            				'rank' => $techn_last_info['divide_rank']
//            			];
//            			$techn_level_info = Db::name('techn_level')->where($techn_level_map)->find();
//            			if(!empty($techn_level_info))
//            			{
//            				//如果技师等级存在
//            				//结算服务分成
//            				if($balance_surplus_price >= 0.01)
//            				{
//            					//技师分成比例
//            					$techn_divide_into = $techn_level_info['divide_into'];
//            					//技师分成金额
//            					$techn_no_money = PriceNumberFormat(($techn_divide_into/100)*$order_info['price']);
//            					//技师服务费用结算数据
//            					$techn_service_data = [
//            						'balance_type' => 1,
//            						'order_id' => $order_info['id'],
//            						'identity_type' => 'techn',
//            						'identity_id' => $order_info['techn_id'],
//            						'divide_into' => $techn_divide_into,
//            						'price' => $order_info['price'],
//            						'no_money' => $techn_no_money >= 0.01 ? $techn_no_money : $order_info['price'],
//            						'yes_money' => $techn_no_money >= 0.01 ? $techn_no_money : $order_info['price'],
//            						'msg' => '技师分成',
//            						'status' => 1,
//            						'add_time' => time(),
//            						'upd_time' => time()
//            					];
//            					$balance_surplus_scale -= $techn_service_data['divide_into'];
//            					$balance_surplus_price -= $techn_service_data['no_money'];
//            					$balance_data[] = $techn_service_data;
//            				}
//            			}
//        		    }
//
//        		}
//
//        		//查看机构结算数据
//        		$proxy_info = Db::name('proxy')->where(['proxy_id' => $order_info['proxy_id'], 'commission' => ['GT', 0]])->find();
//        		if(!empty($proxy_info))
//        		{
//        			if($balance_surplus_price >= 0.01)
//        			{
//        				//机构分成比例
//        				$proxy_commission = $proxy_info['commission'];
//        				//机构分成金额
//        				$proxy_no_money = PriceNumberFormat(($proxy_commission/100)*$order_info['price']);
//        				//机构结算数据
//        				$proxy_service_data = [
//        					'balance_type' => 1,
//        					'order_id' => $order_info['id'],
//        					'identity_type' => 'proxy',
//        					'identity_id' => $proxy_info['proxy_id'],
//        					'divide_into' => $proxy_commission,
//        					'price' => $order_info['price'],
//        					'no_money' => $proxy_no_money >= 0.01 ? $proxy_no_money : $balance_surplus_price,
//        					'yes_money' => $proxy_no_money >= 0.01 ? $proxy_no_money : $balance_surplus_price,
//        					'msg' => '机构分成',
//        					'status' => 1,
//        					'add_time' => time(),
//        					'upd_time' => time()
//        				];
//        				$balance_surplus_scale -= $proxy_service_data['divide_into'];
//        				$balance_surplus_price -= $proxy_service_data['no_money'];
//        				$balance_data[] = $proxy_service_data;
//        			}
//        		}
//        		//系统平台结算数据
//        		if($balance_surplus_price >= 0.01)
//        		{
//        			$balance_data[] = [
//        				'balance_type' => 1,
//        				'order_id' => $order_info['id'],
//        				'identity_type' => 'system',
//        				'identity_id' => 0,
//        				'divide_into' => $balance_surplus_scale,
//        				'price' => $order_info['price'],
//        				'no_money' => $balance_surplus_price,
//        				'yes_money' => $balance_surplus_price,
//        				'msg' => '平台分成',
//        				'status' => 1,
//        				'add_time' => time(),
//        				'upd_time' => time()
//        			];
//        		}
//        		if(!empty($balance_data))
//        		{
//        			$balance_count = Db::name('balance')->insertAll($balance_data);
//        			if($balance_count != count($balance_data))
//        			{
//        				Db::rollback();
//        				//结算数据添加失败
//        				exit();
//        			}
//        		}
//        		//处理结算信息
//        		$balance_list = $balance_data;
//        		$balance_ph_count = 0;
//        		foreach($balance_list as $key => $value)
//        		{
//        			switch($value['identity_type'])
//        			{
//        				//技师
//        				case 'techn':
//        				    //获取技师余额
//        			        $techn_info = Db::name('techn')->where(['id' => $value['identity_id']])->find();
//        			        if(empty($techn_info))
//        					{
//        						continue;
//        					}
//        					// 更新余额数据
//        					$techn_money_data = [
//        						'money' => Db::raw('money+'.$value['no_money']),
//        			            'upd_time' => time()
//        					];
//        					if(!Db::name('techn')->where(['id' => $techn_info['id']])->update($techn_money_data))
//        					{
//        						continue;
//        					}
//        					//技师余额日志
//        					$techn_money_log_id = Db::name('money_log')->insertGetId([
//        			            'identity_type' => 'techn',
//        			            'identity_id' => $techn_info['id'],
//        			            'business_type' => $value['balance_type'] == 2 ? 4 : 5,
//        			            'money_type' => 0,
//        			            'operation_type' => 1,
//        			            'operation_money' => $value['no_money'],
//        			            'original_money' => $techn_info['money'],
//        			            'latest_money' => $techn_info['money']+$value['no_money'],
//        			            'msg' => '技师'.($value['balance_type'] == 2 ? '出行' : '服务').'费用',
//        			            'add_time' => time()
//        			        ]);
//        			        if($techn_money_log_id <= 0)
//        			        {
//        			        	continue;
//        			        }
//        				break;
//        				//机构
//        				case 'proxy':
//        				    //获取机构余额
//        				    $proxy_info = Db::name('proxy')->where(['proxy_id' => $value['identity_id']])->find();
//        				    if(empty($proxy_info))
//        					{
//        						continue;
//        					}
//        					// 更新余额数据
//        					$proxy_money_data = [
//        						'money' => Db::raw('money+'.$value['no_money']),
//        			            'upd_time' => time()
//        					];
//        					if(!Db::name('proxy')->where(['proxy_id' => $proxy_info['proxy_id']])->update($proxy_money_data))
//        					{
//        						continue;
//        					}
//        					//机构余额日志
//        					$proxy_money_log_id = Db::name('money_log')->insertGetId([
//        			            'identity_type' => 'proxy',
//        			            'identity_id' => $proxy_info['proxy_id'],
//        			            'business_type' => 5,
//        			            'money_type' => 0,
//        			            'operation_type' => 1,
//        			            'operation_money' => $value['no_money'],
//        			            'original_money' => $proxy_info['money'],
//        			            'latest_money' => $proxy_info['money']+$value['no_money'],
//        			            'msg' => '机构服务分成费用',
//        			            'add_time' => time()
//        			        ]);
//        			        if($proxy_money_log_id <= 0)
//        			        {
//        			        	continue;
//        			        }
//        			    break;
//        			}
//        			$balance_ph_count++;
//        		}
//        		if($balance_ph_count != count($balance_list))
//        		{
//        			Db::rollback();
//        			//结算记录更新失败
//        			exit();
//        		}
        		//更新父级订单补单状态
        		if(!Db::name('order')->where(['id' => $order_info['id']])->update(['status'=>11,'techn_repair_sid' => $order_id, 'upd_time' => time()]))
                {
                	//事务回滚
                	Db::rollback();
                	//订单更新失败
                	exit();
                }
                
			    Db::name('order_budan')->where(['id' => $params['id']])->update(['type'=>1]);
                
                
        		//提交事务
        		Db::commit();
        		
			}else{
			    Db::name('order_budan')->where(['id' => $params['id']])->update(['type'=>2]);
			}
			
			echo json_encode(['code' => 0, 'msg' => '操作成功']);
		}
	}
	
}